package com.banksoft.admin.service.impl;

import com.banksoft.admin.SystemCache;
import com.banksoft.admin.bean.AmountType;
import com.banksoft.admin.dao.*;
import com.banksoft.admin.entity.*;
import com.banksoft.admin.service.TransferApplyService;
import com.banksoft.common.ConfigHelper;
import com.banksoft.util.StringNumber;
import com.banksoft.util.StringUtil;
import com.banksoft.util.UUIDFactory;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.jstl.core.Config;
import java.util.Date;
import java.util.List;

/**
 * Created by vanjoger on 2017/1/10.
 */
@Service
@Transactional
public class TransferApplyServiceImpl implements TransferApplyService {

    @Autowired
    TransferApplyDao transferApplyDao;
    @Autowired
    UserDao userDao;
    @Autowired
    UserMoneyDao userMoneyDao;
    @Autowired
    BaseMyBatisDao baseMyBatisDao;


    @Override
    public JSONObject save(String userId, Float amount, String remark) {
        String transferAmount = ConfigHelper.GetInstance().GetConfig("TransferAmout");
        User user = this.baseMyBatisDao.findById(UserDao.class,userId);
        if(user==null)
            return StringUtil.FmtResult(false,"用户不存在",null);
        List<UserMoney> moneys = userMoneyDao.findByUserId(user.getId());
        UserMoney money = null;
        if(StringUtil.isNotEmpty(moneys))
            money = moneys.get(0);
        if(money==null)
            return StringUtil.FmtResult(false,"用户余额不足",null);
        if(Float.parseFloat(money.getBonus())<amount.floatValue())
            return StringUtil.FmtResult(false,"用户余额不足",null);

        //计算要出要兑换的现金币金额
        float cashAmount = amount/Float.parseFloat(transferAmount);

        TransferApply apply = new TransferApply();
        apply.setId(UUIDFactory.random());
        apply.setStatus("0");
        apply.setAmount(amount+"");
        apply.setRemark(remark);
        apply.setCashAmount(cashAmount+"");
        apply.setId(userId);
        apply.setCreateTime(new Date().getTime());
        this.baseMyBatisDao.insert(TransferApplyDao.class,apply);

        //冻结购物币
        String beforeBonus = money.getBonus();
        String beforeFrozenAmount = money .getFrozenAmount();
        money.setBonus(StringNumber.sub(beforeBonus,amount+""));
        money.setFrozenAmount(StringNumber.add(beforeFrozenAmount,amount+""));
        this.baseMyBatisDao.update(UserMoneyDao.class,money);

        AmountLog log = new AmountLog();
        log.setId(UUIDFactory.random());
        log.setUserId(user.getId());
        log.setUserName(user.getNickName());
        log.setCreateTime(new Date().getTime());
        log.setBeforeCash(money.getCash());
        log.setBeforeBonus(beforeBonus);
        log.setCash("0");
        log.setBonus("-"+amount);
        log.setAfterCash(money.getCash());
        log.setAfterBonus(money.getBonus());
        log.setType(AmountType.TransferFrozenBonus.name());
        log.setBeforeFrozenAmount(beforeFrozenAmount);
        log.setAfterFrozenAmount(money.getFrozenAmount());
        baseMyBatisDao.insert(AmountLogDao.class,log);

        return StringUtil.FmtResult(true,"申请已提交，待管理员审核",null);
    }

    @Override
    public JSONObject verify(String id, String status, String bz, HttpServletRequest request) {
        TransferApply dto = this.baseMyBatisDao.findById(TransferApplyDao.class,id);
        if(dto==null)
            return StringUtil.FmtResult(false,"没有找到数据",null);
        if(!dto.getStatus().equals("0"))
            return StringUtil.FmtResult(false,"该申请已审核，无需再次审核",null);

        User user = baseMyBatisDao.findById(UserDao.class,dto.getUserId());
        if(user==null)
            return StringUtil.FmtResult(false,"用户不存在",null);

        List<UserMoney> moneys = userMoneyDao.findByUserId(user.getId());
        UserMoney money = null;
        if(StringUtil.isNotEmpty(moneys))
            money = moneys.get(0);
        if (Float.parseFloat(money.getFrozenAmount()) < Float.parseFloat(dto.getAmount()))
            return StringUtil.FmtResult(false, "账户余额不足！", null);

        Admin admin = (Admin) request.getSession().getAttribute(SystemCache.SESSION_ADMIN);
        dto.setStatus(status);
        dto.setShrName(admin.getLoginName());
        dto.setShTime(new Date().getTime());
        dto.setBz(bz);
        this.baseMyBatisDao.update(TransferApplyDao.class,dto);
        //增加资金流水
        AmountLog log = new AmountLog();
        log.setId(UUIDFactory.random());
        log.setCreateTime(new Date().getTime());
        log.setUserId(user.getId());
        log.setUserName(user.getNickName());
        log.setCash(dto.getAmount()+"");
        String beforeFrozenAmount = money.getFrozenAmount();
        String beforeCash = money.getCash();
        String beforeBonus = money.getBonus();

        if(status.equals("1")){//审核通过 则变动余额  新增资金流水
            money.setFrozenAmount(StringNumber.sub(money.getFrozenAmount(),dto.getAmount()));
            money.setCash(StringNumber.add(beforeCash,dto.getCashAmount()));
            this.baseMyBatisDao.update(UserMoneyDao.class,money);

            log.setType(AmountType.TransferFee.name());//扣除转账费用
            log.setBeforeCash(beforeCash);
            log.setBeforeBonus(money.getBonus());
            log.setBeforeFrozenAmount(beforeFrozenAmount);
            log.setAfterCash(money.getCash());
            log.setAfterBonus(money.getBonus());
            log.setAfterFrozenAmount(money.getFrozenAmount());
            this.baseMyBatisDao.insert(AmountLogDao.class,log);

        }else if(status.equals("2")){
            money.setFrozenAmount(StringNumber.sub(money.getFrozenAmount(),dto.getAmount()));
            money.setBonus(StringNumber.add(beforeBonus,dto.getAmount()));
            this.baseMyBatisDao.update(UserMoneyDao.class,money);

            log.setType(AmountType.TransferRejFee.name());//返回提现费用
            log.setBeforeCash(beforeCash);
            log.setBeforeBonus(beforeBonus);
            log.setBeforeFrozenAmount(beforeFrozenAmount);
            log.setAfterCash(money.getCash());
            log.setAfterBonus(money.getBonus());
            log.setAfterFrozenAmount(money.getFrozenAmount());
            this.baseMyBatisDao.insert(AmountLogDao.class,log);
        }

        //保存系统日志
        if("1".equals(status)) {
            saveLog(request,"审核通过转账申请:"+JSONObject.fromObject(dto));
        }else if("2".equals(status)){
            saveLog(request,"审核拒绝转账申请:"+JSONObject.fromObject(dto));
        }
        return StringUtil.FmtResult(true,"操作成功",null);
    }

    /**
     * 保存系统日志
     * @param request
     * @param content
     */
    private void saveLog(HttpServletRequest request,String content){
        Admin admin = (Admin) request.getSession().getAttribute(SystemCache.SESSION_ADMIN);
        SystemLog systemLog = new SystemLog();
        systemLog.setId(UUIDFactory.random());
        systemLog.setOperateName(admin.getLoginName());
        systemLog.setOperateContent(content);
        systemLog.setIp(request.getRemoteHost());
        systemLog.setLogDate(new Date().getTime());
        this.baseMyBatisDao.insert(LogDao.class,systemLog);
    }
}
